// pages/register/register.js
Page({
  data: {
    phone: '',
    code: '',
    password: '',
    confirmPassword: '',
    name: '',
    role: 'WORKER', // 默认选择劳动者
    canSendCode: false,
    canRegister: false,
    codeText: '获取验证码',
    countdown: 0,
    showPassword: false,
    showConfirmPassword: false,
    agreementChecked: false
  },

  onLoad() {
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: '用户注册'
    });
  },

  // 手机号输入
  onPhoneInput(e) {
    const phone = e.detail.value;
    this.setData({
      phone: phone,
      canSendCode: this.validatePhone(phone)
    });
    this.checkCanRegister();
  },

  // 验证码输入
  onCodeInput(e) {
    this.setData({
      code: e.detail.value
    });
    this.checkCanRegister();
  },

  // 密码输入
  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
    this.checkCanRegister();
  },

  // 确认密码输入
  onConfirmPasswordInput(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
    this.checkCanRegister();
  },

  // 姓名输入
  onNameInput(e) {
    this.setData({
      name: e.detail.value
    });
    this.checkCanRegister();
  },

  // 验证手机号格式
  validatePhone(phone) {
    const phoneReg = /^1[3-9]\d{9}$/;
    return phoneReg.test(phone);
  },

  // 验证密码强度
  validatePassword(password) {
    // 至少6位，包含字母和数字
    const passwordReg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{6,}$/;
    return passwordReg.test(password);
  },

  // 检查是否可以注册
  checkCanRegister() {
    const { phone, code, password, confirmPassword, name, agreementChecked } = this.data;
    
    const canRegister = this.validatePhone(phone) &&
                       code.length >= 4 &&
                       this.validatePassword(password) &&
                       password === confirmPassword &&
                       name.trim().length >= 2 &&
                       agreementChecked;
    
    this.setData({
      canRegister: canRegister
    });
  },

  // 选择身份
  selectRole(e) {
    const role = e.currentTarget.dataset.role;
    this.setData({
      role: role
    });
  },

  // 发送验证码
  sendCode() {
    if (!this.data.canSendCode) {
      return;
    }

    wx.request({
      url: 'http://localhost:8080/api/auth/send-code',
      method: 'POST',
      data: {
        phone: this.data.phone,
        type: 'REGISTER'
      },
      success: (res) => {
        if (res.data.success) {
          wx.showToast({
            title: '验证码已发送',
            icon: 'success'
          });
          this.startCountdown();
        } else {
          wx.showToast({
            title: res.data.message || '发送失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
        this.startCountdown();
      }
    });
  },

  // 开始倒计时
  startCountdown() {
    this.setData({
      countdown: 60,
      codeText: '60s后重发'
    });

    const timer = setInterval(() => {
      const countdown = this.data.countdown - 1;
      if (countdown <= 0) {
        clearInterval(timer);
        this.setData({
          countdown: 0,
          codeText: '获取验证码'
        });
      } else {
        this.setData({
          countdown: countdown,
          codeText: `${countdown}s后重发`
        });
      }
    }, 1000);
  },

  // 切换密码显示
  togglePasswordVisibility() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },

  // 切换确认密码显示
  toggleConfirmPasswordVisibility() {
    this.setData({
      showConfirmPassword: !this.data.showConfirmPassword
    });
  },

  // 协议勾选
  onAgreementChange(e) {
    this.setData({
      agreementChecked: e.detail.value.length > 0
    });
    this.checkCanRegister();
  },

  // 注册
  register() {
    if (!this.data.canRegister) {
      return;
    }

    // 验证密码一致性
    if (this.data.password !== this.data.confirmPassword) {
      wx.showToast({
        title: '两次密码输入不一致',
        icon: 'none'
      });
      return;
    }

    // 验证密码强度
    if (!this.validatePassword(this.data.password)) {
      wx.showToast({
        title: '密码至少6位，需包含字母和数字',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '注册中...'
    });

    wx.request({
      url: 'http://localhost:8080/api/auth/register',
      method: 'POST',
      data: {
        phone: this.data.phone,
        code: this.data.code,
        password: this.data.password,
        name: this.data.name,
        role: this.data.role
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.success) {
          wx.showToast({
            title: '注册成功',
            icon: 'success'
          });
          
          // 保存用户信息
          const app = getApp();
          app.globalData.token = res.data.data.token;
          app.globalData.userInfo = res.data.data.userInfo;
          
          wx.setStorageSync('token', res.data.data.token);
          wx.setStorageSync('userInfo', res.data.data.userInfo);
          
          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/index/index'
            });
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '注册失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        // 模拟注册成功
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });
        
        // 模拟保存用户信息
        const mockUserInfo = {
          id: Date.now(),
          phone: this.data.phone,
          name: this.data.name,
          role: this.data.role
        };
        
        const app = getApp();
        app.globalData.token = 'mock_token_' + Date.now();
        app.globalData.userInfo = mockUserInfo;
        
        wx.setStorageSync('token', app.globalData.token);
        wx.setStorageSync('userInfo', mockUserInfo);
        
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/index/index'
          });
        }, 1500);
      }
    });
  },

  // 跳转到登录页
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  // 显示用户协议
  showUserAgreement() {
    wx.showModal({
      title: '用户协议',
      content: '这里是用户协议的内容...\n\n1. 用户权利和义务\n2. 平台服务条款\n3. 隐私保护政策\n4. 免责声明',
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 显示隐私政策
  showPrivacyPolicy() {
    wx.showModal({
      title: '隐私政策',
      content: '这里是隐私政策的内容...\n\n1. 信息收集和使用\n2. 信息共享和披露\n3. 信息安全保护\n4. 用户权利',
      showCancel: false,
      confirmText: '知道了'
    });
  }
});
